<template>
  <!-- 提示框  已超出可匹配量 -->
  <div class="q-pa-md q-gutter-sm">
    <q-dialog
      v-model="box.isErrRow"
      persistent
      transition-show="scale"
      transition-hide="scale"
    >
      <q-card class="bg-pink text-white" style="width: 300px">
        <q-card-section>
          <div class="text-h6">注意</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          已超出可匹配量
        </q-card-section>

        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn flat label="OK" v-close-popup />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>

  <div class="column" style="height: 100%">
    <div style="height: 15px"></div>
    <!-- 表头部分 -->
    <div class="col-1">
      <!-- 表头的输入框和按键 -->
      <q-card flat>
        <!-- 输入框部分 -->
        <div class="q-gutter-md row justify-around">
          <div class="col-0" v-show="!box.isTrue"   >  </div>
          <q-chip v-show="box.isTrue" dense size="lg"  color="teal-9" text-color="white" >确认 </q-chip>
<!--          系统发票单号  -->
          <q-input
                    disable
                    v-model.trim="box.sysReconciliationBillId"
                    type="text"
                    label="系统发票单号"
            >
                <template v-slot:append>
                    <q-icon name="view_stream" size="80%" />
                </template>
            </q-input>
<!--          自定义发票单号-->
            <q-input
                    v-model.trim="box.userReconciliationBillId"
                    type="text"
                    label="自定义发票单号"
            >
                <template v-slot:append>
                    <q-icon name="view_stream" size="80%" />
                </template>
            </q-input>

<!--          供应商-->
          <q-input v-model.trim="box.supplierName" type="text" label="供应商">
            <template v-slot:append>
              <q-icon name="person" size="80%" />
            </template>
          </q-input>
<!--          发票金额-->
          <q-input
            v-model="box.invoiceAmount"
            type="number"
            label="发票金额"
          >
            <template v-slot:append>
              <q-icon name="gesture" size="80%" />
            </template>
          </q-input>
<!--          勾选金额-->
          <q-input
            v-model.trim="box.succeedAmount"
            type="number"
            label="勾选金额"
          >
            <template v-slot:append>
              <q-icon name="gesture" size="80%" />
            </template>
          </q-input>
<!--          差异金额-->
          <q-input
            v-model.trim="box.differenceAmount"
            type="number"
            label="差异金额"
          >
            <template v-slot:append>
              <q-icon name="gesture" size="80%" />
            </template>
          </q-input>


          <!-- <q-input v-model="box.boxPlanDate" type="date" hint="计划交期" /> -->
          <div class="col-0"></div>
        </div>

        <!-- 操作栏 -->
        <div style="height: 15px"></div>
        <div class="row q-gutter-md justify-around">
          <div class="q-gutter-md row items-start justify-around">
            <!-- <div   class=" q-gutter-md row justify-center ">
    <div class=" q-gutter-md  "> -->
            <q-btn-group>
              <q-btn push label="提交" ripple text-color="red-9"  @click="webInsertReconciliationBill" />
              <q-btn push label="查找" ripple text-color="teal-9" @click="searchData" />
              <q-btn push label="确认" ripple fab-max text-color="orange-10"  @click="box.isTrue=!box.isTrue" />
              <q-btn push label="导出" ripple fab-max text-color="green-10"   @click="printExcel"/>
            </q-btn-group>
          </div>

          <!-- 选择框 -->
          <div class="q-pa-md q-gutter-sm ReconciliationBill_tree_font" >匹配收货行</div>
        </div>
        <!-- 间距 -->
        <div style="height: 15px"></div>
          <q-separator spaced="1px" color="teal-8" inset size="6px" />
      </q-card>
    </div>
    <!-- 提示框  添加成功-->
    <q-dialog v-model="box.succeed" position="top">
      <q-card class="bg-primary text-white" style="width: 300px">
        <q-card-section>
          <div class="text-h6">成功提示</div>
        </q-card-section>

        <!-- <q-linear-progress :value="0.7" color="orange" /> -->
        <q-card-actions align="right" class="bg-white text-teal">
          <div></div>
          <div v-show="true">
            <div class="text-h8">{{ box.succeedStr }} ！~</div>
          </div>
          <q-btn
            flat
            color="primary"
            @click="!box.isDialog"
            label="OK"
            v-close-popup
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <!-- 表格 -->
    <q-table
        :rows="box.AlreadyPurchaseOrderList"
        :columns="tabColumnsInsert"
        row-key="purchaseOrderIndex"
        selection="multiple"
        v-model:selected="box.selected"
        :rows-per-page-options="[999]"
      >
<!--   放在q-tableb标签内   :selected-rows-label="getSelectedString"-->
<!--      去掉头部插槽可以显示全选按键-->
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th
            v-for="col in props.cols"
            :key="col.name"
            :props="props"
          >
            <div class="title_font">{{ col.label }}</div>
          </q-th>
        </q-tr>
      </template>

      <!-- 表体部分 -->
      <template v-slot:body="props">
        <q-tr :props="props">
          <!-- 复选框-->
           <q-td key="purchaseOrderIndex" :props="props">
            <q-checkbox v-model="props.selected" color="teal"  @click="chengeState(props)    " />
          </q-td>

          <!--  采购订单号-->
          <q-td key="purchaseOrderId" :props="props">
            {{ props.row.purchaseOrderId }}</q-td
          >
          <!--  采购日期-->
          <q-td key="handleDate" :props="props">
            {{ props.row.handleDate }}</q-td
          >
          <!-- 产品名称 -->
          <q-td key="goodsName" :props="props">
            {{ props.row.goodsName }}</q-td
          >
          <!-- 产品材质 -->
          <q-td key="goodsMaterial" :props="props">
            {{ props.row.goodsMaterial }}</q-td
          >
          <!-- 产品类型 -->
          <q-td key="goodsStyle" :props="props">
            {{ props.row.goodsStyle }}</q-td
          >
          <!-- 产品规格 -->
          <q-td key="goodsSize" :props="props">
            {{ props.row.goodsSize }}</q-td
          >
          <!-- 订单数量 -->
          <q-td key="purchaseOrderQuantity" :props="props">
            <q-badge color="indigo">
              {{ props.row.purchaseOrderQuantity }}
            </q-badge>
          </q-td>

          <!-- 订单单价 -->
          <q-td key="goodsPrice" :props="props">
              <q-badge color="indigo">
              {{ props.row.goodsPrice  }}
            </q-badge>
          </q-td>

          <!-- 订单总金额 -->
          <q-td key="goodsSumPrice" :props="props">
              <q-badge color="pink">
              {{ props.row.goodsSumPrice }}
            </q-badge>
          </q-td>

          <!--          可匹配数量-->
          <q-td key="excessReconciliationBillQuantity" :props="props">
            <q-badge color="teal">
              {{ props.row.excessReconciliationBillQuantity }}
            </q-badge>
          </q-td>
<!--          本次匹配数量-->
          <q-td key="inReconciliationBillQuantity" :props="props">
            <q-badge color="primary">
              {{ props.row.inReconciliationBillQuantity }}
            </q-badge>
            <q-popup-edit v-model="props.row.inReconciliationBillQuantity">
              <q-input
                      :disable ="!props.selected"
                      type="number"
                v-model="props.row.inReconciliationBillQuantity"
                dense
                autofocus
                bottom-slots
              />
            </q-popup-edit>
          </q-td>

        </q-tr>
      </template>

    </q-table>
      <!-- 表格 -->

  </div>

</template>

<script>
import { reactive,  onMounted ,watch,computed } from "vue";
import { toRaw } from '@vue/reactivity'
import {
    getMaxReconciliationBillId,
    getAlreadyPurchaseOrderList,
    insertReconciliationBill,
} from "../../API/ReconciliationBill/ReconciliationBillAPI";
import { addAnyID } from "../../utils/goodsTools";
import {  tabColumnsInsert } from "src/API/ReconciliationBill/ReconciliationBillData.ts";

export default {
  data() {

    //获取获取当前库存量
    onMounted(function () {

      cc();
      async function cc() {
        var res = await getMaxReconciliationBillId();
        console.log(res.data);
        if (res.length>0){
          box.sysReconciliationBillId = addAnyID(res.data[0].reconciliationBillId, "RB");
        }else {
          box.sysReconciliationBillId = addAnyID("RB20000000000", "RB");
        }
      }
    });



    function  searchData(){
      let webReq = JSON.stringify(
          { "supplierName":  box.supplierName}
      );
      searchDataAsync(webReq)
      async function searchDataAsync(webReq) {
        var res = await getAlreadyPurchaseOrderList(webReq);
        box.AlreadyPurchaseOrderList=res.data.list;
        box.url=res.data.url;
        box.AlreadyPurchaseOrderList.forEach(item=>{
          item["inReconciliationBillQuantity"] =0; //初始化金额
        })
      }
    }
    function  chengeState(props){
      // console.log(props)
      box.AlreadyPurchaseOrderList.forEach(item=>{
        if (item.purchaseOrderIndex==props.key){
          item.yesSure=props.selected
          console.log( toRaw(item))
        }
      })
    }
    watch(
        () =>[... box.AlreadyPurchaseOrderList],
        (newVal,oldVal) => {
          box.succeedAmount=0  //已勾选金额
          box.differenceAmount=0 //差异金额

          newVal.forEach(item=>{

            if (!item.yesSure  && item.inReconciliationBillQuantity===0  ){//如果勾选 并初始值是零
                item.inReconciliationBillQuantity=item.purchaseOrderQuantity
                box.succeedAmount=box.succeedAmount+toRaw(item.goodsSumPrice)
            }else if (!item.yesSure  && item.inReconciliationBillQuantity !==0)  {//如果勾选 并初始值不是零
              box.succeedAmount=box.succeedAmount+toRaw(item.goodsSumPrice)
            }else if (item.yesSure ){  //如果取消勾选
              item.inReconciliationBillQuantity=0
              box.succeedAmount=box.succeedAmount-toRaw(item.goodsSumPrice)
            }
          // 判断是否过多勾选了
            if (item.inReconciliationBillQuantity>item.excessReconciliationBillQuantity+item.purchaseOrderQuantity){
              box.isErrRow=true
              item.inReconciliationBillQuantity=0
            }
          })
          box.differenceAmount=box.invoiceAmount -box.succeedAmount
        } ,
        { deep: true }
    );

    function  getSelectedString () {
      if (box.selected.length === 0){
        var SelectedStr=''
      }else if (box.selected.length ===1){
        SelectedStr= box.selected.length + " record "  + "selected of " + box.AlreadyPurchaseOrderList.length
      }else {
        SelectedStr= box.selected.length + " records "  + "selected of " + box.AlreadyPurchaseOrderList.length
      }
      console.log(SelectedStr)
      return SelectedStr
    }

      function webInsertReconciliationBill() {
          // 第一步 检查信息是否输入完整
          let insertData=box.AlreadyPurchaseOrderList.filter((item,index)=>{

              // 1. 添加订单号
              item["sysReconciliationBillId"]=box.sysReconciliationBillId
              item["userReconciliationBillId"]=box.userReconciliationBillId
              // 2. 添加金额
              item["invoiceAmount"]=box.invoiceAmount
              // item["selectedAmount"]=box.selectedAmount
              item["differenceAmount"]=box.differenceAmount

              // 3.剩余可勾选数量
              item["excessReconciliationBillQuantity"]=item.purchaseOrderQuantity -  item.excessReconciliationBillQuantity - item.inReconciliationBillQuantity

              // item.s =Number(item.sumPOAmount)- Number(item.excessInStockAmount)- Number(item.inStockId)
              // delete item.inStockIndex
              return item.inReconciliationBillQuantity !==0
          })

          let JSONinsertData = JSON.stringify(insertData);
          console.log(JSONinsertData);
        insertReconciliationBillAsync(JSONinsertData);

          async function insertReconciliationBillAsync(JSONinsertData) {
            let res = await insertReconciliationBill(JSONinsertData);
            if (res.code==200) {
              console.log(res);
              box.succeed = true;
              box.succeedStr = "成功添加了  "+ insertData.length + "条记录";
              box.AlreadyPurchaseOrderList.length=0
            }
          }
      }


function printExcel () {
  window.open(box.url)
}


      return {
        printExcel,
      // getSelectedString,
        searchData,
          webInsertReconciliationBill,
          box,
          tabColumnsInsert,
        chengeState
    };
  },
};

const box = reactive({
  invoiceAmount:1500,
  selectedAmount:0.0,
  url:null,
  differenceAmount:0.0,
  reconciliationBillAmount: 0.0,
  inReconciliationBillQuantity:0,

  isTrue: false, //确认
  isHeader: false, //智能提示卡片
  isPrompts: false, //开启智能提示
  boxDialog: false,
  succeed: false,
  succeedCount: null,
  isDialog: false, //输入错误消息框
  isErrRow: false, //输入不完整消息框
  errRowData: null, //输入不完整消息框内容
  boxIsShow: false,
  purchaseOrderId:null,
  sysReconciliationBillId: "",
  userReconciliationBillId: "用户自定义发票号01",
  supplierName: "supplierName001",


  selected:[],
  AlreadyPurchaseOrderList: [],
});

</script>
<style>
.ReconciliationBill_tree_font {
  font: 35px sans-serif;
  color: rgb(0, 121, 107);
  font-family:"方正舒体","幼圆";
  font-weight: bolder;
}
.ReconciliationBill_title_font {
  color: rgb(17, 17, 19);
  font-size: 14px;
  font-weight: bolder;
}
.ReconciliationBill_but_float {
  margin-right: 2%;
  float: right;
}

</style>
